package controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pojo.Administrators;
import pojo.Status;
import pojo.Tokens;
import service.AdministratorService;
import service.TokenService;
import service.impl.AdministratorServiceImpl;
import service.impl.TokenServiceImpl;
import utils.JSONUtils;
import utils.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

@RequestMapping("/api/admin")
@RestController
public class AdminController {

    private AdministratorService administratorService = new AdministratorServiceImpl();
    private TokenService tokenService = new TokenServiceImpl();

    /**
     * admin登录
     */
    @PostMapping("/login")
    public void login(@RequestBody Administrators administrator, HttpServletResponse response) throws IOException {


        JSONObject result = new JSONObject();

        Administrators admin = administratorService.login(administrator.getAccount(), administrator.getPassword());
        if (admin != null) {

            long time = System.currentTimeMillis();
            String encryption = TokenUtils.encryption(admin.getId() + "", time);
            Long overTime = TokenUtils.overTime(time);
            Tokens token = new Tokens(encryption, new Timestamp(overTime), admin.getId(), null, null);

            int i = tokenService.registToken(token);

            if (i != -1) {

                JSONObject jsonData = new JSONObject();
                jsonData.put("token", encryption);
                result.put(Status.CODE, Status.OK);
                result.put(Status.MSG, "登录成功");
                result.put("data", jsonData);

            } else {

                result.put(Status.CODE, Status.BAD_REQUEST);
                result.put(Status.MSG, "参数错误");
            }

        } else {
            result.put(Status.CODE, Status.BAD_REQUEST);
            result.put(Status.MSG, "账号密码错误");
        }

        JSONUtils.responseJson(response, result.toJSONString());

    }


    @PostMapping("/logout")
    public void logout(HttpServletRequest req, HttpServletResponse response) throws IOException {

        String accessToken = req.getHeader("AccessToken");
        int i = tokenService.deleteByToken(accessToken);

        JSONObject jsonObject = new JSONObject();
        if (i == -1) {
            jsonObject.put(Status.CODE, Status.BAD_REQUEST);
            jsonObject.put(Status.MSG, "参数错误");
        } else {
            jsonObject.put(Status.CODE, Status.OK);
            jsonObject.put(Status.MSG, "退出登录");
        }
        JSONUtils.responseJson(response, jsonObject.toJSONString());
    }


}
